<template>
  <div>
    <navigate>心理音乐</navigate>
    <div class="play_music">
      <img :src="musicInfo.img" alt="" class="cover_img" />

      <div class="play_box">
        <div class="play_tit">{{ musicInfo.navigate }}</div>
        <div class="play_txt">当前正在播放</div>

        <div class="play_progress">
          <div class="progress_time">
            {{ formatDuration(Math.floor(currentTime)) }}
          </div>
          <div class="progress_bar">
            <div class="file_bar" :style="{ width: progress + '%' }" />
            <div class="sliding_block" :style="{ left: progress + '%' }" />
          </div>
          <div class="progress_time">
            {{ formatDuration(musicInfo?.duration) }}
          </div>
        </div>
        <div class="operation_box">
          <img
            src="@/assets/images/function/no_cycle_icon.png"
            alt=""
            class="small_img"
            v-if="!isLoop"
            @click="
              () => {
                this.isLoop = true;
                this.audio.loop = true;
                this.audio.play();
              }
            "
          />

          <img
            src="@/assets/images/function/cycle_icon.png"
            alt=""
            class="small_img"
            v-else
            @click="
              () => {
                this.isLoop = false;
                this.audio.loop = false;
                this.audio.addEventListener('ended', this.playNextSong, {
                  once: true,
                });
              }
            "
          />

          <img
            src="@/assets/images/function/up_icon.png"
            alt=""
            class="small_img"
            @click="playPreviousSong"
          />
          <img
            v-if="!isPlaying"
            src="@/assets/images/function/pause_icon.png"
            alt=""
            class="big_img"
            @click="playMusic"
          />
          <img
            v-if="isPlaying"
            src="@/assets/images/function/play_icon.png"
            alt=""
            class="big_img"
            @click="playMusic"
          />

          <img
            src="@/assets/images/function/next_icon.png"
            alt=""
            class="small_img"
            @click="playNextSong"
          />
          <img
            src="@/assets/images/function/refresh_icon.png"
            alt=""
            class="small_img"
            @click="fastForward"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  queryMusicInfo,
  queryHotMusiceList,
} from "@/api/funcation/psychologicalMusic";
import { formatDuration } from "@/utils/time";
export default {
  data() {
    return {
      isLoop: false,
      musicInfo: {},
      musicList: [],
      audio: null,
      isPlaying: false,
      progress: 0,
      currentTime: 0,
      musicId: null,
      typeId: null,
      page: 1,
      pageSize: 10,
    };
  },
  created() {
    this.musiceId = this.$route.query.musiceId;
    this.typeId = this.$route.query.typeId;
    if (this.$route.query.type == 1) {
      this.getHotMusicList();
    } else {
      this.getMusicInfo();
    }
  },
  methods: {
    async getHotMusicList() {
      let par = {
        type_id: this.typeId,
      };
      let res = await queryHotMusiceList(par);
      if (res.code == 200) {
        res.data.forEach((x) => {
          if (x.id == this.musiceId) {
            this.musicInfo = x;
            if (this.musicInfo) {
              this.initAudio();
            }
          }
        });
        this.musicList = res.data;
      }
    },
    togglePlay() {
      if (this.isPlaying) {
        // 调用暂停播放的方法
        this.pauseMusic();
      } else {
        // 调用开始播放的方法
        this.startMusic();
      }
      this.isPlaying = !this.isPlaying;
    },
    // 音乐列表
    //音乐列表
    async getMusicInfo(id) {
      let par = {
        page: this.page,
        pageSize: this.pageSize,
        type_id: this.typeId,
      };
      let res = await queryMusicInfo(par);
      if (res.code == 200) {
        res.data.data.forEach((x) => {
          if (x.id == this.musiceId) {
            this.musicInfo = x;
            if (this.musicInfo) {
              this.initAudio();
            }
          }
        });
        this.musicList = res.data.data;
      }
    },

    formatDuration,
    // 初始化音频
    initAudio() {
      if (!this.musicInfo?.file) {
        return;
      }
      this.audio = new Audio(this.musicInfo.file);
      // 根据循环状态设置音频循环属性
      this.audio.loop = this.isLoop;

      // 监听音频加载完成
      this.audio.addEventListener("canplaythrough", () => {
        // 音频加载完成后自动播放
        const playPromise = this.audio.play();
        if (playPromise !== undefined) {
          playPromise
            .then(() => {
              this.isPlaying = true;
              // 添加音频播放结束事件监听
              this.audio.removeEventListener("ended", this.onEnded);
              this.audio.addEventListener("ended", () => {
                if (this.isLoop) {
                  this.audio.currentTime = 0;
                  this.audio.play();
                } else {
                  this.playNextSong();
                }
              });
            })
            .catch((error) => {
              this.isPlaying = false;
            });
        }
      });

      // 监听音频播放进度
      this.audio.addEventListener("timeupdate", this.updateProgress);
      // 监听音频播放结束
      this.audio.addEventListener("ended", this.onEnded);
    },
    toggleLoop() {
      this.isLoop = !this.isLoop;
      if (this.audio) {
        this.audio.loop = this.isLoop;
      }
    },
    playMusic() {
      if (!this.audio) {
        return;
      }

      if (this.isPlaying) {
        this.audio.pause();
        this.isPlaying = false;
      } else {
        // 使用 Promise 处理播放
        const playPromise = this.audio.play();
        if (playPromise !== undefined) {
          playPromise
            .then(() => {
              this.isPlaying = true;
            })
            .catch((error) => {
              this.isPlaying = false;
            });
        }
      }
    },
    // 快进3秒
    fastForward() {
      if (!this.audio) return;
      const newTime = Math.min(this.audio.currentTime + 3, this.audio.duration);
      this.audio.currentTime = newTime;
    },
    fastBackward() {
      if (!this.audio) return;
      const newTime = Math.max(this.audio.currentTime - 3, 0);
      this.audio.currentTime = newTime;
    },
    // 更新进度条
    updateProgress() {
      if (!this.audio) return;
      this.currentTime = this.audio.currentTime;
      this.progress = (this.audio.currentTime / this.audio.duration) * 100;
    },
    // 播放结束处理
    onEnded() {
      this.isPlaying = false;
      this.progress = 0;
      this.currentTime = 0;
    },
    // 播放下一首音乐
    playNextSong() {
      if (this.musicList.length === 0) return;
      if (this.audio) {
        this.audio.pause();
      }
      const currentIndex = this.musicList.findIndex(
        (item) => item.id === this.musicInfo.id
      );
      const nextIndex = (currentIndex + 1) % this.musicList.length;
      this.musicInfo = this.musicList[nextIndex];
      this.initAudio();
    },
    // 播放上一首音乐
    playPreviousSong() {
      if (this.musicList.length === 0) return;
      if (this.audio) {
        this.audio.pause();
      }
      const currentIndex = this.musicList.findIndex(
        (item) => item.id === this.musicInfo.id
      );
      const previousIndex =
        (currentIndex - 1 + this.musicList.length) % this.musicList.length;
      this.musicInfo = this.musicList[previousIndex];
      this.initAudio();
    },
  },
  beforeDestroy() {
    if (this.audio) {
      this.audio.pause();
      this.audio.removeEventListener("canplaythrough", () => {});
      this.audio.removeEventListener("error", () => {});
      this.audio.removeEventListener("timeupdate", this.updateProgress);
      this.audio.removeEventListener("ended", this.onEnded);
      this.audio = null;
    }
  },
};
</script>

<style lang="less" scoped>
.play_music {
  width: 100%;
  height: 100vh;
  background-color: #f4f6fa;
  color: #333333;
}

.cover_img {
  display: block;
  margin: 13.33px auto 0 auto;
  width: 306.67px;
  height: 306.67px;
  border-radius: 10px;
}

.play_box {
  margin: 26.67px 10px 10px 10px;
  padding: 26.67px 10px;
  background: #ffffff;
  border-radius: 10px;
  text-align: center;
}

.play_tit {
  font-size: 20px;
  margin: 58.33px 0 19px;
}

.play_txt {
  opacity: 0.5;
  font-size: 14px;
}

.play_progress {
  display: flex;
  align-items: center;
  margin: 62.67px 0 68.3px;
}

.progress_time {
  font-size: 12px;
}

.progress_bar {
  position: relative;
  margin: 0 8px;
  flex: 1;
  height: 5.33px;

  background: #c2efff;
  border-radius: 2.67px;
}

.file_bar {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background: linear-gradient(90deg, #0eaeff 0%, #0eaeff 100%);
  border-radius: 3px;
  transition: width 0.1s linear;
}

.sliding_block {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 10px;
  height: 6px;
  background: #00aeff;
  border-radius: 4px;
  box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0) inset;
  transition: left 0.1s linear;
}

.operation_box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 6px;
}

.small_img {
  width: 20px;
  height: 20px;
}

.big_img {
  width: 50px;
  height: 50px;
}
</style>
